package com.newmuis.open.codeeval.easy;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * CodeEval.com > Easy Challenges > Reverse Words
 * 
 * Description:
 * 
 * Write a program to reverse the words of an input sentence.
 * 
 * Input sample:
 * 
 * The first argument will be a text file containing multiple sentences, one per line. Possibly
 * empty lines too. e.g.
 * 
 * Hello World
 * Hello CodeEval
 * 
 * Output sample:
 * 
 * Print to stdout, each line with its words reversed, one per line. Empty lines in the input should
 * be ignored. Ensure that there are no trailing empty spaces on each line you print.
 * e.g.
 * 
 * World Hello
 * CodeEval Hello
 * 
 * @author Jonathan Newmuis (jon@newmuis.com)
 * @category easy
 */
public class reverse_words {
	/**
	 * @param args should contain only one CLI argument: the path to an input file which specifies
	 *            the input in the defined format.
	 * @throws IOException if there is a problem reading the given input file.
	 */
	public static void main(final String[] args) throws IOException {
		// Verify input argument length.
		if (args.length < 1) {
			throw new RuntimeException("Must specify input file path.");
		} else if (args.length > 1) {
			throw new RuntimeException("Illegal input arguments specified.");
		}

		// Read file from specified path.
		final BufferedReader reader = new BufferedReader(new FileReader(new File(args[0])));
		String line;

		while ((line = reader.readLine()) != null) {
			// Parse the sentence into words.
			final String[] words = line.split("\\s");

			// Reverse the words.
			final StringBuilder reversedSentenceBuilder = new StringBuilder();
			for (int i = words.length - 1; i >= 0; i--) {
				reversedSentenceBuilder.append(words[i]);

				if (i > 0) {
					reversedSentenceBuilder.append(" ");
				}
			}

			// Output the contents of the buffer.
			System.out.println(reversedSentenceBuilder.toString());
		}
	}

}
